/**
 * Created by sxx on 2017/5/6.
 */
import "./index.less";
import { splrTyp } from "../config.js";

import "../../../unit/common/js/bootstrap_js/table-editable.js";
import "../../../unit/common/js/bootstrap_js/bootstrap-datetimepicker.js";
import "../../../unit/common/js/bootstrap_js/bootstrap-datetimepicker.zh-CN.js";
// 获取模板
import UserBasicInfoTpl from "./tmpl/user_basic_info.handlebars";
import UserBasicInfoEditTpl from "./tmpl/user_basic_info_edit.handlebars";
import bankListTpl from "./tmpl/bank_list.handlebars";
import bankEditTpl from "./tmpl/bank_edit.handlebars";
import aptsListTpl from "./tmpl/user_file_list.handlebars";
import aptsEditTpl from "./tmpl/user_file_edit.handlebars";

let token = sessionStorage.getItem('supplier_token');
let regionList = {};

let canUpdate = true;
let tmpfile = '';  // 上传的资质文件名称

var address = {
    loadAddressScript: function(url, callback) {
        if (!window.tdist_all) {
            var script = $('<script />').attr('type', 'text/javascript');
            if (script.get(0).readyState) {
                script.get(0).onreadystatechange = function() {
                    if (this.readyState == 'loaded' || this.readyState == 'complete') {
                        callback();
                    }
                };
            } else {
                script.get(0).onload = function() {
                    callback();
                }
            }
            script.attr('src', url);
            script.appendTo($('head'));
        } else {
            callback();
        }
    }
};


var filterArea = function(id) {
    var filtered = [];
    var areaData = tdist_all;
    if (typeof(id) === 'number') {
        id = id.toString();
    }
    if (!id) {
        return [];
    }
    for (var i in areaData) {
        if (areaData[i][1] === id) {
            filtered.push({
                id: i,
                areaname: areaData[i][0]
            });
        }
    }
    return filtered;
}
var area2html = function(areaList, level) {
    var html = areaDefault(level);
    $.each(areaList,function(i,el){
        html += '<option value="' + el.id + '">' + el.areaname + '</option>';
    });
    return html;
};

var areaDefault = function(level) {
    if (level === 1) {
        return '<option value="-1">选择省份</option>';
    } else if (level === 2) {
        return '<option value="-2">选择城市</option>';
    } else if (level === 3) {
        return '<option value="-3">选择地区</option>';
    } else {
        return '';
    }
}
var bindEvent = function() {
    $(document).on('touchend', '.J_icon-closed', function(event) {
        event.preventDefault();
        $('.J_address-mask').addClass('hidden');
    });

    // 省份变化联动
    $(document).on('change', '.J_province', function(event) {
        var selected = $(this).val(),
            cities = filterArea(selected),
            counties = filterArea(cities[0].id);
        $('.J_city').html(area2html(cities, 2));
        $('.J_country').html(area2html(counties, 3));

        if (cities.length === 1) {
            $('.J_city').trigger('change');
        }
    });
    // 城市变化联动
    $(document).on('change', '.J_city', function(event) {
        var selected = $(this).val(),
            counties = filterArea(selected);
        $('.J_country').html(area2html(counties, 3));
    });

    // 修改确认
    $(document).on('tap', '.J_editAdress-btn', function(event) {
        var data = vailAndEquip();
        if (data) {
            updateAddress(data, function() {
                typeof config.editSuccessCb === 'function' ? config.editSuccessCb() : '';
            });
        }
    });

    // 点击增加
    $(document).on('tap', '.J_addAdress-btn', function(event) {
        var data = vailAndEquip();
        if (data) {
            addAddress(data, function() {
                typeof config.addSuccessCb === 'function' ? config.addSuccessCb() : '';
            });
        }
    });
    // 点击主按钮提交表单
    $$('.J_main-btn').on('click', function() {
        lib.ridApi.reqFor({
            et: 'function',
            entity_type: 'hms',
            json: {
                marketing: 'hms',
                function: 'lv2ebusiness',
                process: "submitForm"
            }
        });

        submitProduct();
    });
    $$('.J_return-btn').on('click', function() {
        page.back();
    });
    $(document).on('click', '#selWNF_chzn, #selWNF', function() {
        console.log('tap selWNF_chzn');
    })


};


const UserRegister = {

    pageNo: 1,
    pageSize: 20,
    comParm: '',
    init: function() {

        $('.chzn-single').click(function() {
            $(this).toggleClass('chzn-single-with-drop');
            $('#selWNF_chzn').toggleClass('chzn-container-active');
            if ($(this).hasClass('chzn-single-with-drop')) {
                $('.chzn-drop').css('left', '0px');
            } else {
                $('.chzn-drop').css('left', '-9999px');
            }


        });
        $('.chzn-search').on('keyup', 'input', function() {
            let val = $(this).val();
            $.ajax({
                url: HOST_ADDR + '/cpmp/comParm/getByBnkNam/' + val,
                type: 'get',
                dataType: 'json',
                contentType: "application/json",
                success: function(resp) {
                    if (resp.success) {
                        if (resp.data.list.length) {
                            let result = '';
                            $.each(resp.data.list,function(index,item){
                                if (index < 10) {
                                    result = result + `<li class="active-result" data-cod="${item.bnkCod}" data-name="${item.bnkNam}" data-cnty="${item.bnkCnty}">${item.bnkCod}(${item.bnkNam})</li>`;
                                }
                            });
                            $('.chzn-results').html(result);
                        } else {
                            $('.chzn-results').html(`暂无搜索结果`);
                        }
                    }
                },
                error: function(err) {
                    console.log(err);
                }
            });
        });
        $('.chzn-results').on('click', '.active-result', function(e) {
            let cod = $(e.target).data('cod');
            let name = $(e.target).data('name');
            let cnty = $(e.target).data('cnty');
            $('.chzn-single').removeClass('chzn-single-with-drop');
            $('.chzn-single span').text(`${cod}(${name})`);
            $('#selWNF_chzn').removeClass('chzn-container-active');
            $('.chzn-drop').css('left', '-9999px');
            $('.J_bank-add-form .J_bnkCod').val(cod);
            $('.J_bank-add-form .J_bnkNam').val(name);

        });

        $('#bank-edit').on('click', function(e) {
            if ($(e.target).hasClass('search-input')) {
                $(this).toggleClass('chzn-single-with-drop');
                $('#selWNF_chzn').toggleClass('chzn-container-active');
                if ($(this).hasClass('chzn-single-with-drop')) {
                    $('.chzn-drop').css('left', '0px');
                } else {
                    $('.chzn-drop').css('left', '-9999px');
                }
            }
            if ($(e.target).hasClass('active-result')) {
                let cod = $(e.target).data('cod');
                let name = $(e.target).data('name');
                let cnty = $(e.target).data('cnty');
                $('#bank-edit .chzn-single').removeClass('chzn-single-with-drop');
                $('#bank-edit .chzn-single span').text(`${cod}(${name})`);
                $('#bank-edit  #selWNF_chzn').removeClass('chzn-container-active');
                $('#bank-edit  .chzn-drop').css('left', '-9999px');
                $('#bank-edit  .J_bank-edit-form .J_bnkCod').val(cod);
                $('#bank-edit  .J_bank-edit-form .J_bnkNam').val(name);
            }


        });
        $('#bank-edit').on('keyup', '.chzn-search input', function() {
            let val = $(this).val();
            $.ajax({
                url: HOST_ADDR + '/cpmp/comParm/getByBnkNam/' + val,
                type: 'get',
                dataType: 'json',
                contentType: "application/json",
                success: function(resp) {
                    if (resp.success) {
                        if (resp.data.list.length) {
                            let result = '';
                            $.each(resp.data.list,function(index,item){
                                if (index < 10) {
                                    result = result + `<li class="active-result" data-cod="${item.bnkCod}" data-name="${item.bnkNam}" data-cnty="${item.bnkCnty}">${item.bnkCod}(${item.bnkNam})</li>`;
                                }
                            });
                            $('#bank-edit .chzn-results').html(result);
                        } else {
                            $('#bank-edit .chzn-results').html(`暂无搜索结果`);
                        }
                    }
                },
                error: function(err) {
                    console.log(err);
                }
            });
        });
        // $('.chzn-results').on('click', '.active-result', function(e){
        //
        //
        // });

        this.getComParms();
        this.getBasicInfo()
            .then(this.getRegionInfo)
            .then(this.renderBasicInfo)
            .then(this.getBankAccount)
            .then(this.renderBankAccount)
            .then(this.getApts)
            .then(this.renderApts)
            .then(this.bindEvent);
    },

    // 渲染资质文件列表
    renderApts: function(rsp) {
        let aptsHtml = aptsListTpl({ fileList: rsp.data });
        $('.J_file-list').html(aptsHtml)
    },

    // 获取地区信息
    getRegionInfo: function(data) {
        // let CITY_API = HOST_ADDR + '/cpmp/region/region_all';
        // address.loadAddressScript(CITY_API, function() {
        //     resetSelect();
        //     cb && cb();
        // });
        const self = UserRegister;
        return new Promise((resolve, reject) => {
            if (self.regionList) {
                resolve(data);
            }

            const regionList = localStorage.getItem('regionList');
            if (regionList) {
                self.regionList = JSON.parse(regionList);
                resolve(data);
            } else {
                $.ajax({
                    url: HOST_ADDR + '/cpmp/region/region_all',
                    type: 'get',
                    dataType: 'json',
                    contentType: "application/json",
                    success: function(resp) {
                        localStorage.setItem('regionList', JSON.stringify(resp));
                        self.regionList = resp;
                        resolve(data);

                    },
                    error: function(err) {
                        console.log(err);
                    }
                });

            }
        });
    },

    editBankHandler: function() {

        jQuery('#bank-info').addClass('hidden');
        // $.ajax({
        //     url: HOST_ADDR + '/cpmp/region/region_all',
        //     type: 'get',
        //     dataType: 'json',
        //     contentType: "application/json",
        //     success: function(resp) {
        //         regionList = resp;
        //         resolve(resp);
        //
        //     },
        //     error: function(err) {
        //         console.log(err);
        //     }
        // });

        let bankEditHtml = bankListTpl({ bankList: resp.data });

        $('.J_bank-list').html(bankListHtml);

        jQuery('#bank-edit').removeClass('hidden');
    },

    // 绑定事件

    bindEvent: function() {
        let self = UserRegister;
        jQuery('#J_edit-supplier').unbind().click(function() {
            jQuery('#supplier-edit').removeClass('hidden').siblings().addClass('hidden');
            self.getBasicInfo()
                .then(self.getRegionInfo)
                .then(self.getComParms)
                .then(self.renderBasicInfoEdit)
                .then(self.bindEvent);
        });

        $('.J_delete-bank').unbind().click(function() {
            let id = $(this).data('id');
            $.ajax({
                url: HOST_ADDR + '/cpmp/splrSlfMng/delBnkAcnt/' + id,
                type: 'post',
                dataType: 'json',
                contentType: "application/json",
                headers: {
                    'access_token': token,
                    'login_type': 'splr'
                },
                success: function(resp) {
                    if (resp.success) {
                        alert('删除银行账号成功');
                        self.getBankAccount()
                            .then(self.renderBankAccount)
                            .then(self.bindEvent);
                    } else {
                        alert(resp.msgInf);
                    }
                },
                error: function(err) {
                    console.log(err);
                }

            });
        });

        $('.J_acntGrup, .J_ptnrTyp, .J_hasCreditCode').off().on('change', function() {
            self.checkInput();
        });

        jQuery('.J_edit-bank').unbind().click(function() {
            // self.editBankHandler();
            let id = $(this).data('id');
            $.ajax({
                url: HOST_ADDR + '/cpmp/splrSlfMng/bnkAcnt/' + id,
                type: 'get',
                dataType: 'json',
                headers: {
                    'access_token': token,
                    'login_type': 'splr'
                },
                contentType: "application/json",
                success: function(resp) {
                    if (resp.success) {
                        switch (resp.data.bnkCod) {
                            case '1000001':
                                resp.data.isBank1 = true;
                                break;
                            case '1000002':
                                resp.data.isBank2 = true;
                                break;
                            case '1000003':
                                resp.data.isBank3 = true;
                                break;
                            case '1000004':
                                resp.data.isBank4 = true;
                                break;
                            default:
                                resp.data.isBank1 = true;

                        }
                        let bankHtml = bankEditTpl(resp.data);
                        $('#bank-edit').html(bankHtml).removeClass('hidden').siblings().addClass('hidden');
                        $('.J_bank-back').unbind().click(function() {
                            jQuery('#bank-info').removeClass('hidden').siblings().addClass('hidden');
                        });
                        $('#J_submit-bank-acnt').unbind().click(function() {
                            let data = {
                                "acntNam": $('.J_bank-edit-form').find('.J_acntNam').val(),
                                "bnkAcnt": $('.J_bank-edit-form').find('.J_bnkAcnt').val(),
                                "bnkAcntId": id,
                                "bnkNam": $('.J_bank-edit-form').find('.J_bnkNam').val(),
                                "bnkCod": $('.J_bank-edit-form').find('.J_bnkCod').val()
                            };
                            $.ajax({
                                url: HOST_ADDR + '/cpmp/splrSlfMng/modBnkAcnt',
                                type: 'post',
                                data: JSON.stringify(data),
                                dataType: 'json',
                                headers: {
                                    'access_token': token,
                                    'login_type': 'splr'
                                },
                                contentType: "application/json",
                                success: function(resp) {
                                    if (resp.success) {
                                        alert('修改银行账号成功');
                                        self.getBankAccount()
                                            .then(self.renderBankAccount)
                                            .then(self.bindEvent);
                                        jQuery('#bank-info').removeClass('hidden').siblings().addClass('hidden');
                                    } else {
                                        alert(resp.msgInf);
                                    }
                                },
                                error: function(err) {
                                    console.log(err);
                                }

                            })
                        });

                    } else {
                        alert(resp.msgInf);
                    }
                },
                error: function(err) {
                    console.log(err);
                }
            });

        });

        $('#tab_1_3').off().on('click', function(e) {
            if($(e.target).hasClass('J_aptUpload')){   // 上传资质文件
                let formData = new FormData();
                let file = $('.J_aptFile')[0].files[0];
                console.log(file);
                if (file) {
                    formData.append('file', file);
                    $.ajax({
                        url: HOST_ADDR + '/cpmp/file/upload/apt',
                        type: 'post',
                        data: formData,
                        processData: false,
                        contentType: false,
                        headers: {
                            'access_token': token,
                            'login_type': 'splr'
                        },
                        success: function(resp) {
                            if (resp.success) {
                                tmpfile = resp.data;
                                alert('上传资质文件成功');
                            } else {
                                alert('上传资质文件失败');
                            }
                        },
                        error: function(err) {
                            console.log(err);
                        }
                    });
                } else {
                    alert('请先上传资质文件');
                }
            }

            if ($(e.target).hasClass('J_edit-file')) {
                let id = $(e.target).data('id');
                let aptNam = $(e.target).data('aptnam');
                let aptVal = $(e.target).data('aptval');
                let aptInTime = $(e.target).data('aptintime');
                let crfcOgnz = $(e.target).data('crfcognz');
                let data = {
                    id,
                    aptNam,
                    aptVal,
                    aptInTime,
                    crfcOgnz
                }
                let aptsHtml = aptsEditTpl(data);
                $('#file-edit').html(aptsHtml).removeClass('hidden').siblings().addClass('hidden');
                jQuery('#file-edit .datetimepicker').datetimepicker({
                    language: 'zh-CN',
                    weekStart: 1,
                    todayBtn: 1,
                    autoclose: 1,
                    todayHighlight: 1,
                    startView: 2,
                    minView: 2, //0表示分钟（默认），1表示小时，而2表示天 ,3.月 , 4.年
                    forceParse: 1,
                    showMeridian: 0,
                    // format: 'yyyy-mm-dd hh:ii:ss', ///
                    format: 'yyyy-mm-dd' ///
                }); // self.bindEvent();

            }
            if ($(e.target).hasClass('J_file-back')) {
                $('#file-info').removeClass('hidden').siblings().addClass('hidden');
            }
            if ($(e.target).hasClass('J_submit-file-info')) {
                let $this = $(e.target);
                let $fileEditForm = $('.J_file-edit-form');

                let id = $this.data('id');
                let aptNam = tmpfile;
                let aptVal = $fileEditForm.find('.J_aptVal').val();
                // let file = $('.J_aptFile')[0].files[0];
                let crfcOgnz = $fileEditForm.find('.J_crfcOgnz').val();
                let aptInTim = $fileEditForm.find('.J_aptInTim').val()+' 23:59:59';
                let formData = {
                    'aptId': id,
                    'crfcOgnz': crfcOgnz,
                    'aptInTim': Date.parse(new Date(aptInTim)),
                    'aptNam': aptNam
                };
                let header = {
                    'access_token': token,
                    'login_type': 'splr'
                }
                console.log(header);
                $.ajax({
                    url: HOST_ADDR + '/cpmp/splrSlfMng/upload/apt',
                    type: 'post',
                    headers: header,
                    data: JSON.stringify(formData),
                    contentType:"application/json",
                    success: function(resp) {
                        if (resp.success) {
                            alert('上传文件成功');
                            self.getApts().then(self.renderApts);
                            $('#file-info').removeClass('hidden').siblings().addClass('hidden');
                        } else {
                            alert(resp.msgInf);
                        }
                    },
                    error: function(err) {
                        console.log(err);
                    }
                })
            }
        });


        $('#tab_1_1').on('click', '.J_back', function() {
            $('#supplier-info').removeClass('hidden').siblings().addClass('hidden');
        })

        $('.J_todo').unbind().click(function() {
            alert('技术大大正在全力开发中，请稍候...');
        })

        jQuery('.J_add-bank').unbind().click(function() {

            jQuery('#bank-info').addClass('hidden');
            jQuery('#bank-add').removeClass('hidden');
        });
        jQuery('.J_bank-back').unbind().click(function() {
            jQuery('#bank-info').removeClass('hidden').siblings().addClass('hidden');
        });
        $('#J_add-bank-acnt').unbind().click(function() {
            self.setBankInfo();
        });

        jQuery('.datetimepicker').datetimepicker({
            language: 'zh-CN',
            weekStart: 1,
            todayBtn: 1,
            autoclose: 1,
            todayHighlight: 1,
            startView: 2,
            forceParse: 1,
            showMeridian: 0,
            format: 'yyyy-mm-dd hh:ii:ss' ///
        });
        $(document).on('change', function(e) {
            if ($(e.target).hasClass('J_rgst-region')) {
                const region = $(e.target).val();
                if(region=="" || region == null){ // 省份
                    $('.J_rgst-city').html("");
                    $('.J_rgst-district').html("");
                    return false;
                }
                const cityList = self.regionList[region].cities;
                let cityDom = '';
                //const districtList = cityList
                for (let i in cityList) {
                    cityDom += `<option value="${i}">${cityList[i].name}</option>`
                }
                $('.J_rgst-city').html(cityDom);
                const city = $('.J_rgst-city').val();
                const districtList = cityList[city].towns;
                let districtDom = '';
                for (let i in districtList) {
                    districtDom += `<option value="${i}">${districtList[i].name}</option>`;
                }
                $('.J_rgst-district').html(districtDom);

            }
            if ($(e.target).hasClass('J_rgst-city')) {
                const region = $('.J_rgst-region').val();
                const city = $(e.target).val();
                const districtList = self.regionList[region].cities[city].towns;
                let districtDom = '';
                for (let i in districtList) {
                    districtDom += `<option value="${i}">${districtList[i].name}</option>`;
                }
                $('.J_rgst-district').html(districtDom);

            }
        });
        //$(document).off().on('change', '.J_rgst-city', function(){
    },

    // 处理用户基本信息数据

    dealWithBasicInfo(rsp) {
        return new Promise((resolve, reject) => {
            $.ajax({
                url: HOST_ADDR + '/cpmp/splrSlfMng/info',
                type: 'get',
                dataType: 'json',
                headers: {
                    'access_token': token,
                    'login_type': 'splr'
                },
                contentType: "application/json",
                success: function(resp) {
                    if (resp.success) {
                        resolve(resp);
                    } else {
                        alert(resp.msgInf);
                    }
                },
                error: function(err) {
                    console.log(err);
                }
            });
        });
    },

    // 处理数据
    formatData(data) {
        let self = UserRegister;
        data.hasCreditCode = data.hasCreditCode == '1' ? '是' : '否';
        data.fullAddr = data.rgstAddr ? data.rgstAddr : '';
        data.contact = data.contact ? data.contact : '';
        let region, city, district;
        let regDate = new Date(data.regTim);
        if (data.region) {
            data.region = $.trim(data.region);
            region = self.regionList[data.region].name;
            city = data.city ? self.regionList[data.region].cities[$.trim(data.city)].name : '';
            district = (data.city && data.district) ? self.regionList[data.region].cities[$.trim(data.city)].towns[$.trim(data.district)].name : '';
            data.fullAddr = region + city + district + (data.rgstAddr ? data.rgstAddr : '');
        }
        data.fullTel = '';
        data.fullFax = '';
        if(data.telEx || data.telephone){
            if((data.telEx && !data.telephone) || (!data.telEx && data.telephone)){
                data.fullTel = data.telEx ? data.telEx : data.telephone;
            }else{
                data.fullTel = data.telEx + ' - ' + data.telephone;
            }
        }
        if(data.faxEx || data.fax){
            if((data.faxEx && !data.fax) || (!data.faxEx && data.fax)){
                data.fullFax = data.faxEx ? data.faxEx : data.fax;
            }else{
                data.fullFax = data.faxEx + ' - ' + data.fax;
            }
        }
        data.regTimFmt = `${regDate.getFullYear()}年${regDate.getMonth()+1}月${regDate.getDate()}日`;
        $.each(self.comParm.data.IDST_TYP,function(index,item){
            if (item.parmCod === data.idst1) {
                data.idst1 = item.parmVal;
            }
            if (item.parmCod === data.idst2) {
                data.idst2 = item.parmVal;
            }
        });
        $.each(self.comParm.data.SPLR_TYP,function(index,item){
            if (item.parmCod == data.ptnrTyp) {
                data.ptnrTyp = item.parmVal;
            }
        });
        $.each(self.comParm.data.CPN_NTR,function(index,item){
            if (item.parmCod == data.cpnNtr) {
                data.cpnNtr = item.parmVal;
            }
        });
        return data;
    },

    // 渲染用户基本信息
    renderBasicInfo(rsp) {
        const self = UserRegister;
        return new Promise((resolve, reject) => {
            let data = rsp.data;
            data.ptnrTypFmt = splrTyp[data.classification];
            if (!self.comParm) {
                self.getComParms().then(() => {
                    data = self.formatData(data);

                    let basicInfoHtml = UserBasicInfoTpl({ data });
                    $('#J_basic-user-info').html(basicInfoHtml);

                })
            } else {
                data = self.formatData(data);

                let basicInfoHtml = UserBasicInfoTpl({ data });

                $('#J_basic-user-info').html(basicInfoHtml);

            }
            resolve();
        });
    },
    getComParms(data) {
        const self = UserRegister;
        return new Promise((resolve, reject) => {
            const parmTyps = 'CPN_NTR,SPLR_TYP,IDST_TYP,GRUP_ACNT_GRUP,PTNR_TYP';
            const url = HOST_ADDR + '/cpmp/comParm/getByParmTyps/' + parmTyps;
            $.ajax({
                url: HOST_ADDR + '/cpmp/comParm/getByParmTyps/' + parmTyps,
                type: 'get',
                dataType: 'json',
                contentType: 'application/json',
                success: function(resp) {
                    var GRUP_ACNT_GRUPList = [];
                    $.each(resp.data.GRUP_ACNT_GRUP,function(index,item){
                        if (item.parmCod == 'Z005') {   // 集团外部结算客商  默认放在第一位
                            GRUP_ACNT_GRUPList.splice(0, 0, item);
                        }else{
                            GRUP_ACNT_GRUPList.push(item);
                        }
                    });
                    resp.data.GRUP_ACNT_GRUP = GRUP_ACNT_GRUPList;
                    self.comParm = resp;
                    resolve(data);
                },
                error: function(err) {
                    console.log(err);
                }
            })
        })
    },

    checkInput() {
        let acntGrup = $('.J_acntGrup').val();
        let $hasCreditCode = $('.J_hasCreditCode');
        let $ifNoCreditCode = $('.J_ifNoCreditCode');
        let $J_crdtCod = $('.J_crdtCod');
        let hasCreditCode = $hasCreditCode.val();
        let ptnrTyp = $('.J_ptnrTyp').val();
        let $shuiMsg = $('.J_shuiMsg');

        $shuiMsg.addClass('hidden');

        if (acntGrup === 'Z001') {
            $('.J_ptnrTyp').attr('disabled','disabled').closest('.control-group').removeClass('bitian');
            $hasCreditCode.attr('disabled', false).closest('.control-group').addClass('bitian');
            if (hasCreditCode == 1) {
                $ifNoCreditCode.attr('disabled','disabled').closest('.control-group').removeClass('bitian');

                $J_crdtCod.attr('disabled',false).closest('.control-group').addClass('bitian');

            } else {
                $ifNoCreditCode.attr('disabled',false).closest('.control-group').addClass('bitian');

                $J_crdtCod.attr('disabled','disabled').closest('.control-group').removeClass('bitian');
            }
        } else if (acntGrup === 'Z005' || acntGrup === 'Z007') {
            $('.J_ptnrTyp').attr('disabled',false).closest('.control-group').addClass('bitian');
            if (ptnrTyp == 1) {
                $hasCreditCode.attr('disabled',false).closest('.control-group').addClass('bitian');
                if (hasCreditCode == 1) {
                    $ifNoCreditCode.attr('disabled','disabled').closest('.control-group').removeClass('bitian');

                    $J_crdtCod.attr('disabled',false).closest('.control-group').addClass('bitian');

                } else {
                    $ifNoCreditCode.attr('disabled',false).closest('.control-group').addClass('bitian');

                    $J_crdtCod.attr('disabled','disabled').closest('.control-group').removeClass('bitian');
                }
            } else if (ptnrTyp == 2 || ptnrTyp == 3) {
                $hasCreditCode.attr('disabled','disabled').closest('.control-group').removeClass('bitian');
                $ifNoCreditCode.attr('disabled','disabled').closest('.control-group').removeClass('bitian');
                $J_crdtCod.attr('disabled',false).closest('.control-group').removeClass('bitian');
                $shuiMsg.removeClass('hidden');

            } else if (ptnrTyp == 4) {
                $hasCreditCode.attr('disabled','disabled').closest('.control-group').removeClass('bitian');
                $ifNoCreditCode.attr('disabled','disabled').closest('.control-group').removeClass('bitian');
                $J_crdtCod.attr('disabled',false).closest('.control-group').addClass('bitian');


            } else if (ptnrTyp == 5 || ptnrTyp == 6) {
                $hasCreditCode.attr('disabled','disabled').closest('.control-group').removeClass('bitian');
                $ifNoCreditCode.attr('disabled','disabled').closest('.control-group').removeClass('bitian');
                $J_crdtCod.attr('disabled',false).closest('.control-group').removeClass('bitian');
            }

        } else if (acntGrup === 'Z011') {
            $('.J_ptnrTyp').attr('disabled','disabled').closest('.control-group').removeClass('bitian');
            $hasCreditCode.attr('disabled','disabled').closest('.control-group').removeClass('bitian');
            $ifNoCreditCode.attr('disabled','disabled').closest('.control-group').removeClass('bitian');
            $J_crdtCod.attr('disabled','disabled').closest('.control-group').removeClass('bitian');


        }

    },

    // 渲染编辑详细信息页面
    renderBasicInfoEdit(rsp) {
        const self = UserRegister;
        return new Promise((resolve, reject) => {
            let data = rsp.data;
            let cityList;
            let districtList;
            $.each(self.comParm.data.SPLR_TYP,function(index,item){
                if (item.parmCod == data.classification) {
                    item.isSelected = true;
                }
            });
            $.each(self.comParm.data.CPN_NTR,function(index,item){
                if (item.parmCod == data.cpnNtr) {
                    item.isSelected = true;
                }
            });
            $.each(self.comParm.data.IDST_TYP,function(index,item){
                if (item.parmCod == data.idst1) {
                    item.isSelected1 = true;
                }
                if (item.parmCod == data.idst2) {
                    item.isSelected2 = true;
                }
            });
            $.each(self.comParm.data.GRUP_ACNT_GRUP,function(index,item){
                if (item.parmCod == data.acntGrup) {
                    item.isSelected = true;
                }
            });
            $.each(self.comParm.data.PTNR_TYP,function(index,item){
                if (item.parmCod == data.ptnrTyp) {
                    item.isSelected = true;
                }
            });

            if (data.region) {
                data.region = $.trim(data.region);
                cityList = self.regionList[data.region].cities;
                self.regionList[data.region].isSelected = true;

                if (data.city) {
                    data.city = $.trim(data.city);
                    cityList[data.city].isSelected = true;
                    districtList = self.regionList[data.region].cities[data.city].towns;
                    if (data.district && districtList[data.district]) {
                        districtList[data.district].isSelected = true;
                    }
                }

            }
            data.hasCreditCode = data.hasCreditCode == 1;
            //  self.regionList = Object.keys(self.regionList).map(function(k){return self.regionList[k]});
            let regDate = new Date(data.regTim);
            let regMonth = (regDate.getMonth() + 1) > 9 ? (regDate.getMonth() + 1) : ('0' + (regDate.getMonth() + 1));
            let regDay = regDate.getDate() > 9 ? regDate.getDate() : ('0' + regDate.getDate());
            let regHour = regDate.getHours() > 9 ? regDate.getHours() : ('0' + regDate.getHours());
            let regMinute = regDate.getMinutes() > 9 ? regDate.getMinutes() : ('0' + regDate.getMinutes());
            let regSecond = regDate.getSeconds() > 9 ? regDate.getSeconds() : ('0' + regDate.getSeconds());
            data.regTimFmt = `${regDate.getFullYear()}-${regMonth}-${regDay} ${regHour}:${regMinute}:${regSecond}`;
            let basicInfoEditHtml = UserBasicInfoEditTpl({ "regionList": self.regionList, data, "comParm": self.comParm.data, cityList, districtList });
            $('.J_basic-info-edit').html(basicInfoEditHtml);
            self.checkInput();

            jQuery('#J_submit-user-info').unbind().click(function() {
                if (canUpdate) {
                    canUpdate = false;
                    UserRegister.updateBasicInfo();
                }
            });
            resolve();
        });
    },

    // 获取用户基本信息
    getBasicInfo: function() {
        return new Promise((resolve, reject) => {
            $.ajax({
                url: HOST_ADDR + '/cpmp/splrSlfMng/info/',
                type: 'get',
                dataType: 'json',
                headers: {
                    'access_token': token,
                    'login_type': 'splr'
                },
                contentType: "application/json",
                success: function(resp) {
                    if (resp.success) {
                        resolve(resp);
                    } else {
                        alert(resp.msgInf);
                    }
                },
                error: function(err) {
                    console.log(err);
                }
            });
        });

    },

    // 获取银行账号信息
    getBankAccount: function() {
        let self = UserRegister;
        return new Promise((resolve, reject) => {
            $.ajax({
                url: HOST_ADDR + `/cpmp/splrSlfMng/bnkAcnt/${self.pageNo}/${self.pageSize}`,
                type: 'get',
                dataType: 'json',
                headers: {
                    'access_token': token,
                    'login_type': 'splr'
                },
                contentType: "application/json",
                success: function(resp) {
                    if (resp.success) {
                        resolve(resp);
                        // location.href = 'index.html';
                    } else {
                        alert(resp.msgInf);
                    }
                },
                error: function(err) {
                    console.log(err);
                }
            });
        });
    },

    renderBankAccount: function(resp) {
        let bankListHtml = bankListTpl({ bankList: resp.data.list });

        $('.J_bank-list').html(bankListHtml);
    },
    //获取资质文件列表

    getApts: function() {
        return new Promise((resolve, reject) => {
            $.ajax({
                url: HOST_ADDR + '/cpmp/splrSlfMng/apts',
                type: 'get',
                dataType: 'json',
                headers: {
                    'access_token': token,
                    'login_type': 'splr'
                },
                contentType: "application/json",
                success: function(resp) {
                    if (resp.success) {
                        resolve(resp);
                    } else {
                        alert(resp.msgInf);
                    }
                },
                error: function(err) {
                    console.log(err);
                }
            });
        });
    },


    // 更新用户信息

    updateBasicInfo: function() {
        let self = this;
        let $basicInfoForm = $('.J_basic-info-edit');
        let regTim = $basicInfoForm.find('.J_regTim').val();
        let regTimFmt = new Date(regTim).getTime();
        let data2 = {
            "acntGrup": $basicInfoForm.find('.J_acntGrup').val(),
            "region": $basicInfoForm.find('.J_rgst-region').val(),
            "district": $basicInfoForm.find('.J_rgst-district').val(),
            "city": $basicInfoForm.find('.J_rgst-city').val(),
            "classification": $basicInfoForm.find('.J_classification').val(),
            "crdtCod": $basicInfoForm.find('.J_crdtCod').val().trim(),
            "cpnNtr": $basicInfoForm.find('.J_cpnNtr').val(),
            "ctrlUsr": $basicInfoForm.find('.J_ctrlUsr').val(),
            "dbusiLice": $basicInfoForm.find('.J_dbusiLice').val().trim(),
            "email": $basicInfoForm.find('.J_email').val().trim(),
            "fax": $basicInfoForm.find('.J_fax').val().trim(),
            "faxEx": $basicInfoForm.find('.J_faxEx').val(),
            "fullNam": $basicInfoForm.find('.J_fullNam').val().trim(),
            "hasCreditCode": $basicInfoForm.find('.J_hasCreditCode').val(),
            "idst": $basicInfoForm.find('.J_idst').val(),
            "idst1": $basicInfoForm.find('.J_idst1').val(),
            "idst2": $basicInfoForm.find('.J_idst2').val(),
            "lglIdntCad": $basicInfoForm.find('.J_lglIdntCod').val(),
            "lglUser": $basicInfoForm.find('.J_lglUser').val(),
            "mob": $basicInfoForm.find('.J_mob').val(),
            "oprRng": $basicInfoForm.find('.J_oprRng').val(),
            "orgCod": $basicInfoForm.find('.J_orgCod').val().trim(),
            "parentCpn": $basicInfoForm.find('.J_parentCpn').val().trim(),
            "postCod": $basicInfoForm.find('.J_postCod').val().trim(),
            "ptnrTyp": $basicInfoForm.find('.J_ptnrTyp').val(),
            "regCptl": $basicInfoForm.find('.J_regCptl').val(),
            "regTim": regTimFmt,
            "rgstAddr": $basicInfoForm.find('.J_rgstAddr').val(),
            "shortNam": $basicInfoForm.find('.J_shortNam').val().trim(),
            "suprGrup": $basicInfoForm.find('.J_suprGrup').val(),
            "taxCod": $basicInfoForm.find('.J_taxCod').val().trim(),
            "telEx": $basicInfoForm.find('.J_telEx').val().trim(),
            "telephone": $basicInfoForm.find('.J_telephone').val().trim(),
            "trdePtnr": $basicInfoForm.find('.J_trdePtnr').val().trim(),
            "contact": $basicInfoForm.find('.J_contact').val().trim(),
            "secName": $basicInfoForm.find('.J_secName').val().trim()
        }

        if(!data2.telEx || !data2.telephone){
            alert('请填写电话');
            canUpdate = true;
            return;
        }
        for(var i=0;i<$(".control-group.bitian").length;i++){
            var item = $(".control-group.bitian")[i];
            var labelname = $(item).find("label.control-label").text().slice(0,-1);
            var value = $(item).find(".controls .m-wrap").val().trim();
            if(!value){
                alert(labelname+"不能为空！");
                canUpdate = true;
                return;
            }
        }

        // if (!data2.fullNam) {
        //     alert('请填写客商名称');
        //     canUpdate = true;
        //     return;
        // }
        // if (!data2.contact) {
        //     alert('请填写联系人');
        //     canUpdate = true;
        //     return;
        // }
        // if (!data2.mob) {
        //     alert('请填写移动电话');
        //     canUpdate = true;
        //     return;
        // }
        // if (data2.acntGrup === 'Z001') {
        //     if (data2.hasCreditCode == 1) {
        //         if (!data2.crdtCod) {
        //             alert('请填写社会信用统一代码');
        //             canUpdate = true;
        //             return;
        //         }
        //     } else {
        //         if (!data2.taxCod || !data2.dbusiLice || !data2.orgCod) {
        //             alert('请填写完整税务登记号、营业执照号、组织机构代码');
        //             canUpdate = true;
        //             return;
        //         }
        //     }
        // } else if (data2.acntGrup === 'Z005' || data2.acntGrup === 'Z007') {
        //     if (!data2.ptnrTyp) {
        //         alert('请选择客商类别');
        //         canUpdate = true;
        //         return;
        //     }
        //     if (data2.ptnrTyp == 1) {
        //         if (data2.hasCreditCode == 1) {
        //             if (!data2.crdtCod) {
        //                 alert('请填写社会信用统一代码');
        //                 canUpdate = true;
        //                 return;
        //             }
        //         } else {
        //             if (!data2.taxCod || !data2.dbusiLice || !data2.orgCod) {
        //                 alert('请填写完整税务登记号、营业执照号、组织机构代码');
        //                 canUpdate = true;
        //                 return;
        //             }
        //         }
        //     } else if (data2.ptnrTyp == 4) {
        //         if (!data2.crdtCod) {
        //             alert('请填写社会信用统一代码');
        //             canUpdate = true;
        //             return;
        //         }
        //     }
        // }
        $.ajax({
            url: HOST_ADDR + '/cpmp/splrSlfMng/info',
            type: 'post',
            data: JSON.stringify(data2),
            dataType: 'json',
            headers: {
                'access_token': token,
                'login_type': 'splr'
            },
            contentType: "application/json",
            success: function(resp) {
                if (resp.success) {
                    alert('修改注册信息成功');
                    sessionStorage.setItem('fullNam', data2.fullNam);
                    self.getBasicInfo()
                        .then(self.getRegionInfo)
                        .then(self.getComParms)
                        .then(self.renderBasicInfo)
                        .then(self.getApts)
                        .then(self.renderApts)
                        .then(self.bindEvent);
                    jQuery('#supplier-info').removeClass('hidden');
                    jQuery('#supplier-edit').addClass('hidden');
                } else {
                    alert(resp.msgInf);
                }
                canUpdate = true;
            },
            error: function(err) {
                console.log(err);
            }

        });
    },

    resetBankAdd: function() {
        let $bankAddForm = $('.J_bank-add-form');
        $bankAddForm.find('.J_acntNam').val('');
        $bankAddForm.find('.J_bnkAcnt').val('');
        $bankAddForm.find('.J_bnkNam').val('');
    },

    setBankInfo: function() {
        let self = UserRegister;
        let $bankAddForm = $('.J_bank-add-form');
        let acntNam = $bankAddForm.find('.J_acntNam').val();
        let bnkAcnt = $bankAddForm.find('.J_bnkAcnt').val();
        let bnkNam = $bankAddForm.find('.J_bnkNam').val();
        let bnkCod = $bankAddForm.find('.J_bnkCod').val();

        let data = {
            acntNam,
            bnkAcnt,
            bnkCod,
            bnkNam
        };

        $.ajax({
            url: HOST_ADDR + '/cpmp/splrSlfMng/bnkAcnt',
            type: 'post',
            data: JSON.stringify(data),
            dataType: 'json',
            headers: {
                'access_token': token,
                'login_type': 'splr'
            },
            contentType: "application/json",
            success: function(resp) {
                if (resp.success) {
                    alert('添加银行账号成功成功');
                    self.resetBankAdd();
                    self.getBankAccount()
                        .then(self.renderBankAccount)
                        .then(self.bindEvent);
                    jQuery('#bank-info').removeClass('hidden').siblings().addClass('hidden');
                } else {
                    alert(resp.msgInf);
                }
            },
            error: function(err) {
                console.log(err);
            }

        })
    }
}




App.init();
UserRegister.init();